import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { AdminUser, LoginForm, LoginResponse } from '@/types/admin'
import { api, API_ENDPOINTS } from '@/utils/api'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<AdminUser | null>(null)
  const token = ref<string | null>(null)
  const isLoading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const isEditor = computed(() => user.value?.role === 'editor')

  // 初始化状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('admin_token')
    const savedUser = localStorage.getItem('admin_user')
    
    if (savedToken && savedUser) {
      token.value = savedToken
      try {
        user.value = JSON.parse(savedUser)
      } catch {
        logout()
      }
    }
  }

  // 登录
  const login = async (loginForm: LoginForm): Promise<boolean> => {
    try {
      isLoading.value = true
      
      // 模拟登录API调用（因为API文档中没有认证接口，这里使用模拟数据）
      await new Promise(resolve => setTimeout(resolve, 1000))
      
      // 模拟登录验证
      if (loginForm.username === 'admin' && loginForm.password === 'admin123') {
        const mockResponse: LoginResponse = {
          token: 'mock-jwt-token-' + Date.now(),
          user: {
            id: 1,
            username: 'admin',
            email: 'admin@example.com',
            role: 'admin',
            avatar: '',
            lastLoginAt: new Date().toISOString(),
            createdAt: new Date().toISOString()
          },
          expiresIn: 7200
        }

        token.value = mockResponse.token
        user.value = mockResponse.user

        // 保存到本地存储
        localStorage.setItem('admin_token', mockResponse.token)
        localStorage.setItem('admin_user', JSON.stringify(mockResponse.user))

        if (loginForm.remember) {
          localStorage.setItem('admin_remember', 'true')
        }

        ElMessage.success('登录成功')
        return true
      } else {
        ElMessage.error('用户名或密码错误')
        return false
      }
    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error('登录失败，请重试')
      return false
    } finally {
      isLoading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 如果有真实的登出接口，可以调用
      // await api.post(API_ENDPOINTS.LOGOUT)
      
      // 清除状态
      user.value = null
      token.value = null
      
      // 清除本地存储
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
      localStorage.removeItem('admin_remember')
      
      ElMessage.success('已安全退出')
    } catch (error) {
      console.error('登出失败:', error)
      // 即使登出失败也要清除本地状态
      user.value = null
      token.value = null
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_user')
      localStorage.removeItem('admin_remember')
    }
  }

  // 获取用户信息
  const fetchUserProfile = async () => {
    try {
      // 如果有真实的用户信息接口，可以调用
      // const response = await api.get(API_ENDPOINTS.PROFILE)
      // user.value = response.data
      return user.value
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData: Partial<AdminUser>) => {
    try {
      // 如果有真实的更新接口，可以调用
      // const response = await api.put(API_ENDPOINTS.PROFILE, profileData)
      
      // 模拟更新
      if (user.value) {
        user.value = { ...user.value, ...profileData }
        localStorage.setItem('admin_user', JSON.stringify(user.value))
      }
      
      ElMessage.success('用户信息更新成功')
    } catch (error) {
      console.error('更新用户信息失败:', error)
      ElMessage.error('更新失败，请重试')
      throw error
    }
  }

  // 检查权限
  const hasPermission = (permission: string): boolean => {
    if (!user.value) return false
    
    // 管理员拥有所有权限
    if (user.value.role === 'admin') return true
    
    // 编辑器权限检查（可以根据需要扩展）
    if (user.value.role === 'editor') {
      const editorPermissions = [
        'lessons:read',
        'lessons:create',
        'lessons:update',
        'categories:read',
        'tags:read',
        'tags:create',
        'codeExamples:read',
        'codeExamples:create',
        'codeExamples:update',
        'upload:create'
      ]
      return editorPermissions.includes(permission)
    }
    
    return false
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    isEditor,
    
    // 方法
    initAuth,
    login,
    logout,
    fetchUserProfile,
    updateProfile,
    hasPermission
  }
}) 